<template>
  <pageHeader :title="title" :breadCrumb="breadCrumb" :show-back="true">
  </pageHeader>
  <div>
    <a-tabs @change="searchState" type="line">
      <a-tab-pane :key="1" title="采购收货"> </a-tab-pane>
      <a-tab-pane :key="2" title="委外收货"> </a-tab-pane>
    </a-tabs>
  </div>
  <div class="search-box">
    <div>
      <a-space>
        <!-- <a-select
            :style="{ width: '120px' }"
            placeholder="请选择"
            v-model="currSelectVal"
            :default-value="currSelectVal"
          >
            <a-option value="entryNumber">收货单编号</a-option>
          </a-select> -->
        <a-input-search
          search-button
          :style="{ width: 'auto' }"
          placeholder="请输入收货单编号"
          v-model="currSelectSearch"
          @search="search"
        />
        <a-button type="outline" @click="reset">
          <template #icon>
            <icon-refresh />
          </template>
          <template #default>重置</template>
        </a-button>
      </a-space>
    </div>
    <div>
      <a-space>
        <a-button status="success">
          <template #icon>
            <icon-download />
          </template>
          <template #default>导入</template>
        </a-button>

        <a-button status="warning">
          <template #icon>
            <icon-export :rotate="-90" />
          </template>
          <template #default>导出</template>
        </a-button>

        <a-button type="primary" @click="showFormHeaderSetting"
          >表头设置</a-button
        >
      </a-space>
    </div>
  </div>
  <div style="padding: 10px">
    <tableTurn :tableData="getData" :args="args" ref="tableRef">
      <a-table-column :width="80" align="center">
        <template #title> 序号 </template>
        <template #cell="{ rowIndex }">
          {{ rowIndex + 1 }}
        </template>
      </a-table-column>
      <a-table-column
        v-for="item in selectedHeader"
        :key="item.code"
        :title="item.name"
        :data-index="item.code"
        :width="150"
        align="center"
      >
        <template v-if="item.code === 'applyTime'" #cell="{ record }">
          {{ dayjs(record.applyTime).format('YYYY-MM-DD HH:mm:ss') }}
        </template>

        <template v-else-if="item.code === 'createdAt'" #cell="{ record }">
          {{ dayjs(record.createdAt).format('YYYY-MM-DD') }}
        </template>

        <template v-else-if="item.code === 'priority'" #cell="{ record }">
          <a-typography-text
            v-if="record.priority === 1"
            style="color: #999999"
          >
            低
          </a-typography-text>
          <a-typography-text v-if="record.priority === 2" type="primary">
            中
          </a-typography-text>
          <a-typography-text v-if="record.priority === 3" type="warning">
            高
          </a-typography-text>
          <a-typography-text v-if="record.priority === 4" type="danger">
            紧急
          </a-typography-text>
        </template>

        <template v-else-if="item.code === 'okState'" #cell="{ record }">
          <div
            class="status"
            :style="{
              color: Status.filter((ele) => ele.id === record.state)[0]
                ?.backgroundColor,
            }"
          >
            <p
              :style="{
                'background': Status.filter((ele) => ele.id === record.state)[0]
                  ?.backgroundColor,
                'box-shadow': `0px 0px 5px`,
              }"
            ></p>
            {{ Status.filter((ele) => ele.id === record.state)[0]?.value }}
          </div>
        </template>
        <template
          v-else-if="item.code === 'inspectionStaffName'"
          #cell="{ record }"
        >
          {{ record.inspectionStaffName || '--' }}
        </template>

        <template
          v-else-if="item.code === 'warehouseStaffName'"
          #cell="{ record }"
        >
          {{ record.warehouseStaffName || '--' }}
        </template>
      </a-table-column>
      <a-table-column :width="200" title="质检状态" align="center">
        <template #cell="{ record }">
          <div
            class="status"
            :style="{
              color: inspectionState.filter(
                (ele) => ele.id === record.inspectionState
              )[0]?.backgroundColor,
            }"
          >
            <p
              :style="{
                'background': inspectionState.filter(
                  (ele) => ele.id === record.inspectionState
                )[0]?.backgroundColor,
                'box-shadow': `0px 0px 5px`,
              }"
            ></p>
            {{
              inspectionState.filter(
                (ele) => ele.id === record.inspectionState
              )[0]?.value
            }}
          </div>
        </template>
      </a-table-column>
      <a-table-column :width="100" fixed="right" title="操作" align="center">
        <template #title> 操作 </template>
        <template #cell="{ record }">
          <a-tooltip content="详情">
            <IconFont
              type="icon-details-def"
              :size="26"
              :style="{
                marginRight: '10px',
                cursor: 'pointer',
              }"
              @click="goDeliveryDetails(record.id, record.entryType)"
            />
          </a-tooltip>
          <!-- <div
            v-if="record.state !== 1"
            @click="goDeliveryDetails(record.id, record.entryType)"
          >
            <a-button type="text">申请详情</a-button>
          </div> -->
        </template>
      </a-table-column>
    </tableTurn>
  </div>
  <FormHeaderSetting
    v-model:visible="formHeaderSettingVisible"
    :resultList="headerSetting.list"
    @headerSave="headerSave"
  ></FormHeaderSetting>
</template>

<script lang="ts" setup>
  import { reactive, ref, computed, onMounted } from 'vue';
  import { useRouter } from 'vue-router';
  import dayjs from 'dayjs';
  // import {
  //   getPurchaseHeader,
  //   PUTPurchaseHeader,
  //   getPurchaseApplyList,
  //   delPurchaseApplyList,
  //   PutPurchaseApplyList,
  // } from '@/api/buy-management/buy-apply/index';
  import {
    GetWarehouseEntryAll,
    GetHeaderAll,
    putHeader,
    delWarehouseEntry,
    putWarehouseEntryState,
  } from '@/api/inventory-management/warehousing-management/receiving-management/index';

  const router = useRouter();
  const title: string = '收货管理';
  const breadCrumb: string[] = ['库存管理', '入库管理', '收货管理'];
  const modelVisible = ref(false);
  const formHeaderSettingVisible = ref(false);
  let tableRef: any = ref(); // 储存table的ref
  let currSelectVal = ref(); // 储存当前下拉选择框的值
  let currSelectSearch = ref(''); // 储存下拉选择框对应的搜索框的值
  const modelCauseVisible = ref(false);
  const userState = ref();
  const beginTime = ref();
  const endTime = ref();
  const entryType = ref(1);
  const saveUserId = ref<any>(
    JSON.parse(sessionStorage.getItem('loginInfo') as any)
  );

  // 储存表头数据
  const priorityData = ref(); // 储存搜索优先级的值
  const headerSetting = reactive<any>({
    list: [],
  });

  const Status = [
    { id: 1, value: '已收货', backgroundColor: '#cccccc' },
    { id: 2, value: '已收货', backgroundColor: '#009933' },
  ];

  const inspectionState = [
    { id: 1, value: '待质检', backgroundColor: '#999999' },
    { id: 2, value: '质检通过', backgroundColor: '#009933' },
    { id: 2, value: '部分通过质检', backgroundColor: '#4e8bfb' },
    { id: 2, value: '质检不通过', backgroundColor: '#dc143c' },
  ];

  // 表格配置
  const args = reactive({
    stripe: false,

    scroll: {
      y: 2000,
      x: 500,
    },
    bordered: {
      headerCell: true,
    },
    rowKey: 'id', // 批量选择按钮 以合同名称来作为key
  });

  const getData = async (page: any) => {
    try {
      const msg: any = {};
      if (currSelectSearch.value) msg.number = currSelectSearch.value;
      if (userState.value) msg.state = userState.value;
      if (priorityData.value) msg.priority = priorityData.value;
      if (entryType.value) msg.entryType = entryType.value;

      let res = await GetWarehouseEntryAll({
        ...page,
        ...msg,
      });

      if (res.content === null || res.content === undefined) {
        res.content = [];
      }

      res.content.map((item: any) => {
        item.show = false;
        return item;
      });

      return Promise.resolve(res);
    } catch (err: unknown) {
      console.log(err);
    }
  };

  const columns1 = ref([
    {
      code: 'number',
      isDefault: 1,
      name: '收货单号',
    },
    {
      code: 'purchaseOrderNumber',
      isDefault: 1,
      name: '关联采购订单号',
    },
    {
      code: 'supplierName',
      isDefault: 1,
      name: '供应商名称',
    },
    {
      code: 'location',
      isDefault: 1,
      name: '暂存区域',
    },
    {
      code: 'entryStaffName',
      isDefault: 1,
      name: '收货人',
    },
    {
      code: 'inspectionStaffName',
      isDefault: 1,
      name: '质检员',
    },

    {
      code: 'okState',
      isDefault: 1,
      name: '收货状态',
    },
  ]);

  const columns2 = ref([
    {
      code: 'number',
      isDefault: 1,
      name: '收货单号',
    },
    {
      code: 'outsourcingNumber',
      isDefault: 1,
      name: '关联委外单号',
    },
    {
      code: 'supplierName',
      isDefault: 1,
      name: '供应商名称',
    },
    {
      code: 'location',
      isDefault: 1,
      name: '暂存区域',
    },
    {
      code: 'entryStaffName',
      isDefault: 1,
      name: '收货人',
    },
    {
      code: 'inspectionStaffName',
      isDefault: 1,
      name: '质检员',
    },

    {
      code: 'okState',
      isDefault: 1,
      name: '收货状态',
    },
  ]);

  const showFormHeaderSetting = () => {
    formHeaderSettingVisible.value = true;
  };

  const headerSettingData = async () => {
    try {
      const res = await GetHeaderAll({
        userId: saveUserId.value.id,
        listType: entryType.value,
      });
      if (res.extends) {
        headerSetting.list = res.extends;
      } else {
        if (entryType.value === 1) headerSetting.list = columns1.value;
        if (entryType.value === 2) headerSetting.list = columns2.value;
      }
      // headerSetting.list = res.extends ? res.extends : columns.value;
    } catch (err: unknown) {
      console.log(err);
    }
  };
  headerSettingData();

  const reset = () => {
    currSelectVal.value = '';
    currSelectSearch.value = '';
    userState.value = undefined;
    priorityData.value = undefined;
    tableRef.value.loadData();
  };

  const headerSave = async (val: any) => {
    try {
      const data = {
        userId: saveUserId.value.id,
        listType: entryType.value,
        extend: JSON.stringify(val),
      };
      await putHeader(data);
      headerSetting.list = [...val];
    } catch (err: unknown) {
      console.log(err);
    }
  };

  const SeeCauseDate = ref();
  const view = (content: string) => {
    SeeCauseDate.value = content;
    modelCauseVisible.value = true;
  };

  const searchState = (key: number) => {
    entryType.value = key;
    headerSettingData();
    reset();
    // tableRef.value.loadData();
  };

  const addBuyApply = (e: number) => {
    router.push({
      name: 'ReceivingAdd',
      query: { entryStaffId: e },
    });
  };

  const goDetails = (id?: number) => {
    router.push({
      name: 'ReceivingDetails',
      query: { id },
    });
  };

  const edit = (id: number) => {
    router.push({
      name: 'editApplyPurchase',
      query: { id },
    });
  };

  const goDelivery = async (id: number) => {
    await putWarehouseEntryState({ id });
    tableRef.value.loadData();
  };

  // 在表格上显示的表头
  // const selectedHeader = computed(() => {});
  const selectedHeader = computed({
    get: () => {
      const arr: any = [];
      headerSetting.list.forEach((item: any) => {
        if (item.isDefault === 1) {
          arr.push(item);
        }
      });
      return arr;
    },
    set: (val) => {
      console.log(val);
    },
  });

  const SeeDate = ref();

  const See = (item: any) => {
    modelVisible.value = true;
    SeeDate.value = item;
  };

  const search = () => {
    tableRef.value.loadData();
  };

  const del = async (id: number) => {
    await delWarehouseEntry({ id });
    tableRef.value.loadData();
  };

  const goDeliveryDetails = async (id: number, type: number) => {
    router.push({
      name: 'DeliveryReceivingDetails',
      query: { id, type },
    });
  };

  const goInspection = (id: number) => {
    router.push({
      name: 'InspectionDetails',
      query: { id },
    });
  };
</script>

<style scoped lang="less">
  // .content-head {
  // }
  .search-box {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    padding: 0px 10px;
  }

  :deep(.arco-space-item) {
    margin-top: 10px;
  }
  .Detail-item {
    cursor: pointer;
  }

  :deep(.arco-tabs-content) {
    padding-top: 0px;
  }

  .status {
    display: flex;
    align-items: center;
    justify-content: center;

    p {
      width: 12px;
      height: 12px;
      border-radius: 50%;
      margin-right: 10px;
    }
  }
</style>
